﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using System.Text;
using System.Threading.Tasks;
using WFExtended.Framework.ServiceModel;

namespace WFExtended.Twitter
{
    /// <summary>
    /// Twitter Exception Observer
    /// </summary>
    public class TwitterExceptionObserver : IServiceErrorObserver
    {
        /// <summary>
        /// Called when [error].
        /// </summary>
        /// <param name="exception">The exception.</param>
        /// <exception cref="RateLimitException"></exception>
        /// <exception cref="ForbiddenException"></exception>
        /// <exception cref="NotFoundException"></exception>
        public void OnError(Exception exception)
        {
            WebException we = exception as WebException;

            if(we == null)
                 we = exception.InnerException as WebException;

            if(we == null)
                return;

            HttpWebResponse response = (HttpWebResponse) we.Response;
            int status = (int)response.StatusCode;

            switch (status)
            {
                case 429:
                    throw new RateLimitException(
                        String.Format("Too many requests for {0}", response.ResponseUri.AbsolutePath), exception)
                        {
                            Resource = response.ResponseUri.AbsolutePath,
                            Query = response.ResponseUri.Query
                        };

                case 403:
                case 401:
                    throw new ForbiddenException(
                        String.Format("Forbidden Access for uri {0} & params {1}", response.ResponseUri.AbsolutePath, response.ResponseUri.Query), exception)
                        {
                            Resource = response.ResponseUri.AbsolutePath,
                            Query = response.ResponseUri.Query
                        };
                case 404:
                case 400:
                    throw new NotFoundException(
                        String.Format("Resource {0} Not Found", response.ResponseUri.ToString()), exception)
                    {
                        Resource = response.ResponseUri.AbsolutePath,
                        Query = response.ResponseUri.Query
                    };
                default:
                    break;
            }

        }

    }
}
